# 中间件
from django.shortcuts import redirect
from django.urls import reverse
import re


class ShopMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        print('ShopMiddleware')

    def __call__(self, request):
        path = request.path
        # print(path)
        # 判断管理是否登录了
        # 定义不登录允许访问的【白名单
        urllist = [
            '/myadmin/login/',
            '/myadmin/dologin/',
            '/myadmin/logout/',
            '/myadmin/check_code/',
            '/web/login/',
            '/web/dologin/',
            '/web/logout/',
            '/web/verify/',
        ]
        # 判断当前url是否已 /myadmin 开头, 并且不在urllist中 才判断
        if re.match(r'^/myadmin', path) and (path not in urllist):
            # 判断是否登录
            if 'adminuser' not in request.session:
                # 重定向
                return redirect(reverse('myadmin_login'))

        # 判断大堂点餐请求是否登录【判断session中是否有webuser
        if re.match(r'^/web', path) and (path not in urllist):
            # 判断是否登录
            if 'webuser' not in request.session:
                # 重定向
                return redirect(reverse('web_login'))

        # 判断当前url是否已 /mobile 开头, 并且不在urllist中 才判断【移动端
        mobile_list = [
            '/mobile/member/logout/',
            '/mobile/do_register/',
            '/mobile/register/',
        ]  # 白名单
        if re.match(r'^/mobile', path) and (path not in mobile_list):
            # 判断是否登录【在session中有没有mobileuser
            if 'mobileuser' not in request.session:
                # 重定向
                return redirect(reverse('mobile_register'))

        response = self.get_response(request)
        return response
